import _ from 'lodash';
import { queryPackage, queryRecord, updatePack, createRecord, editRecord } from '../services/task';

export default {
  namespace: 'record',
  state: {
    packages: [],
    records: [],
    packageKeys: [],
    recordKeys: [],
  },
  effects: {
    *queryPackage({
      payload: { id },
    }, { put }) {
      const data = yield queryPackage({ id });
      // packages: any[]
      const packages = _.get(data, 'packages');
      let keys = [];
      // 合并keys
      _.each(packages, (item) => {
        keys = _.union(keys, Object.keys(item));
      });

      yield put({
        type: 'save',
        payload: {
          packages,
          packageKeys: keys,
        },
      });
    },
    *queryRecord({ payload: { id } }, { put }) {
      const data = yield queryRecord({ id });
      const records = _.get(data, 'items');
      let keys = [];
      _.each(records, (item) => {
        keys = _.union(keys, Object.keys(item));
      });
      yield put({
        type: 'save',
        payload: {
          records,
          recordKeys: keys,
        },
      });
    },
    *updatePack({ payload: { value, onEnd } }) {
      try {
        const values = _.cloneDeep(value);
        const id = values.id;
        delete values.id;
        yield updatePack({
          info: values,
          package: id,
        });
      } catch (e) {
        return onEnd(e.message || e);
      }
      onEnd();
    },
    *createRecord({ payload: { value, onEnd } }) {
      try {
        const {
          lineNumber, task, ...rest
        } = value;
        yield createRecord({
          lineNumber,
          task,
          content: rest,
        });
      } catch (e) {
        return onEnd(e.message || e);
      }
      onEnd();
    },
    *editRecord({ payload: { value, onEnd } }) {
      try {
        yield editRecord(value);
      } catch (e) {
        return onEnd(e.message || e);
      }
      onEnd();
    },
  },
  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },
};
